from socket import socket

# 1.创建套接字对象
server = socket()
# 2.绑定ip和端口
server.bind(('10.7.156.120', 8088))
# 3.准备监听
server.listen(512)
# 4.让服务一直运行
while True:
    print('开始监听...')
    # 1.接受请求
    connection, address = server.accept()
    re1 = connection.recv(1024)
    re1_msg = re1.decode(encoding='utf-8')
    if re1_msg == ' 1':
        connection.send('进入持续交流模式'.encode())
        # 2.持续交流
        while True:
            # 接收消息
            re_data = connection.recv(1024)
            re_message = re_data.decode(encoding='utf-8')
            print('%s:%s' % (address[0], re_message))
            if re_message == '拜拜' or re_message == 'ByeBye':
                connection.close()
                break
            elif re_message == '你好':
                connection.send('你也好'.encode())
            else:
                connection.send('1'.encode())
    elif re1_msg == ' 2':
        # 发送消息
        # message = input('server:')
        with open('海贼王/shanji.jpeg', 'rb') as f:
            message = f.read()
        connection.send(message)
        if message == '拜拜' or message == 'ByeBye':
            connection.close()
            break
    elif re1_msg == ' 3':
        connection.send('服务器关闭'.encode())
        connection.close()
        break
    else:
        connection.send('服务器关闭'.encode())
        connection.close()
        break
